package com.chuanke.ckfamily.service.common;

import com.chuanke.ckfamily.service.common.impl.RedisLockUtil;

public abstract class SynizedExcuter {

    public void run(CacheService cacheService, String key, long timeOut) {
        RedisLockUtil lockUtil = null;
        try {
            lockUtil = cacheService.getLock(key.toString());
            Long tvalue =  (Long) cacheService.get(key);
            if (!needExecute(tvalue, timeOut)) {
                return;
            }

            cacheService.set(key, System.currentTimeMillis());

        } catch (Exception e) {
            e.printStackTrace();
            return;

        } finally {
            if (lockUtil != null) {
                lockUtil.unlock();
            }

        }

        try {
           excute();

        } finally {
            try {
                lockUtil = cacheService.getLock(key);
                cacheService.delete(key);

            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                if (lockUtil != null) {
                    lockUtil.unlock();
                }

            }
        }
    }

    /**
     * 需要执行的业务；实现此方法即可
     */
    public abstract void excute();

    private boolean needExecute(Long time, Long timeOut) {
        if (time == null) {
            return true;
        }

        return (System.currentTimeMillis() - time) > timeOut;
    }
}
